package auctionhaus

import grails.converters.JSON

class SendMailService {
    boolean transactional = false

    //Tell the JMS plugin that this is a message endpoint
    static expose = ['jms']
    static destination = "queue.sendmail"


    //The Mail plugin service
    def mailService

    def onMessage(emailMessage) {
        //println("GOT MESSAGE: $emailMessage")
        sendMail(emailMessage)
        //Return null to avoid poison messages
        return null
    }

    private sendMail(emailMessage) {
        try {
            Email email = JSON.parse(emailMessage)

            mailService.sendMail {
                to email.to
                from email.fromField
                subject email.subject
                body(view: "/email/email", model: [greeting: email.body, id:email.id])
                //body(view: "/email/email", model: [winner: email.winner])

            }
            
        } catch (Exception e) {
            println("Failed to send Message: $emailMessage because: $e")
            log.error("Failed to send email ${emailMessage}", e)
        }
    }
}